package com.qishi.mySocket;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class MyHttpServer {

    //System.getProperty("user.dir")获取当前项目的根目录
    //File.separator表示路径分隔符 due在linux系统和windows系统下路径分隔符是不一样的，用这个来表示跨平台性
    //下面的WEB_ROOT是指这个项目下的webroot目录下的路径
    public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";

    private static final String SHUIDOWN_COMMAND = "/SHUTDOWN";

    private boolean shutDown = false;

    public static void main(String[] args) {
        MyHttpServer httpServer = new MyHttpServer();
        httpServer.await();

    }

    public void await() {
        ServerSocket serverSocket = null;
        int port = 8080;
        try {
            //port 监听的端口号
            //backlog 指的是保存客户端连接请求的最大队列长度，一旦超越这个长度，服务器端点开始拒绝客户端的连接请求。
            //监听客户端的地址，通常是本地服务即指localhost
            serverSocket = new ServerSocket(port,1,InetAddress.getByName("127.0.0.1"));
        }catch (IOException e) {
            e.printStackTrace();
            //非正常退出程序，无论程序是否在执行都退出程序，关闭jvm
            System.exit(1);
        }


        //等待request请求
        while(!shutDown) {
            Socket socket = null;
            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                socket = serverSocket.accept();
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();

                //创建MyRequest
                MyRequest request = new MyRequest(inputStream);
                request.parse();

                //创建MyResponse对象
                MyResponse response = new MyResponse(outputStream);
                response.setRequest(request);
                response.sendStaticResource();

                //关闭socket
                socket.close();

                shutDown = request.getUri().equals(SHUIDOWN_COMMAND);
            }catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }
}
